<?php

namespace app\admin\controller\dahui;

use app\common\controller\Backend;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Session;

/**
 * 补缴管理
 *
 * @icon fa fa-circle-o
 */
class Bujiao extends Backend
{
    
    /**
     * Bujiao模型对象
     * @var \app\admin\model\dahui\Bujiao
     */
    protected $model = null;

    protected $searchFields = 'id,idnumber,taobaoname,kehu.name,kehu.mobile,kehu.bankcardnumber';

    protected $noNeedRight = ['saveadd', 'changetstatus4', 'plbjstatus0','plbjstatus1','plbjstatus2','lsdd','audit', 'gzls', 'addhis', 'editkehunote', 'changetstatus', 'changetstatus2','changebjstatus', 'edit1', 'edit2', 'allaudit'];

    protected $tuikuan = 0;
    protected $caozuo = 0;
    protected $audit = 0;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\dahui\Bujiao;

        $this->assignconfig('audit', $this->auth->check('dahui/dingdan/audit'));
        $this->assignconfig('luru', $this->auth->check('dahui/dingdan/luru'));
        $this->assignconfig('caozuo', $this->auth->check('dahui/dingdan/caozuo'));
        $this->assignconfig('tuikuan', $this->auth->check('dahui/newtk/tuikuan'));

        $this->view->assign("businesstypeList", $this->model->getBusinesstypeList());
        $this->view->assign("auditstatusList", $this->model->getAuditstatusList());
        $this->view->assign("overduestatusList", $this->model->getOverduestatusList());
        $this->view->assign("preprocessingList", $this->model->getPreprocessingList());
        $this->view->assign("refundornotList", $this->model->getRefundornotList());

        $this->tuikuan = $this->auth->check('dahui/newtk/tuikuan');
        $this->caozuo = $this->auth->check('dahui/dingdan/caozuo');
        $this->audit = $this->auth->check('dahui/dingdan/audit');

        $dahui = $this->auth->check('dahui/dingdan/audit')
            && $this->auth->check('dahui/dingdan/luru') && $this->auth->check('dahui/dingdan/caozuo');
        $this->assignconfig('dahui', $dahui);
        $this->view->assign("dahui", $dahui);

    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->with(['kehu'])
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->with(['kehu'])
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            $list = collection($list)->toArray();
            if ($limit == 0) {
                //导出
//                foreach ($list as &$row) {
//                    $row['idnumber'] = $this->importstr($row['idnumber']);
//                    $row['paymentnumber'] = $this->importstr($row['paymentnumber']);
//                }
            }

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    public function importstr($one) {

        return "' ".$one;
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
//                    $params['orderdate'] = date('Y-m-d H:i:s');
//
//                    $params['luruman'] = $this->auth->nickname;
//                    $total = $this->model
//                        ->where('businesstype', $params['businesstype'])
//                        ->where('idnumber', $params['idnumber'])
//                        ->where('yearpayment', $params['yearpayment'])
//                        ->count();
//
//                    if ($total > 0) {
//                        $this->error(__('系统已存在同一客户同一业务相同的补缴年月!'));
//                    }
//
//                    $result = $this->model->allowField(true)->save($params);
//
                    $params = $this->setquanxianlog($params);
                    $kehu = \app\admin\model\dahui\Kehu::get(['idnumber' => $params['idnumber']]);
                    if ($kehu) {
                        $kehu->name = $params['name'];
                        $kehu->mobile = $params['mobile'];
                        $kehu = $this->setquanxianlog2($kehu);
                        $kehu->save();
                    } else {
                        $kehu = new \app\admin\model\dahui\Kehu;
                        $result2 = $kehu->allowField(true)->save($params);
                    }

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $Gongshi = new \app\admin\model\dahui\Gongshi;
        $companyList = collection($Gongshi->field('businesstype, name, minimumcardinality, proportion')->select())->toArray();
        $this->view->assign("companyList", $companyList);

        return $this->view->fetch();
    }

    //添加已使用ajax单独处理
    public function saveadd()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $params['orderdate'] = date('Y-m-d H:i:s');
                    if (isset($params['preprocessing']) && $params['preprocessing'] == '是') {
                        //预处理

                    } else {
                        if (empty($params['businesstype'])) {
                            $this->error(__('业务类型必填'));
                        }
                        if (empty($params['idnumber'])) {
                            $this->error(__('身份证必填'));
                        }
                        if (empty($params['yearpayment'])) {
                            $this->error(__('缴纳年月必填'));
                        }
                        $total = $this->model
                            ->where('businesstype', $params['businesstype'])
                            ->where('idnumber', $params['idnumber'])
                            ->where('yearpayment', $params['yearpayment'])
                            ->count();
                        if ($total > 0) {
                            $this->error(__('系统已存在同一客户同一业务相同的缴纳年月!'));
                        }

                    }
                    $params = $this->setquanxianlog($params);

                    $result = $this->model->allowField(true)->save($params);

                    if (isset($params['idnumber']) && strlen($params['idnumber']) > 10) {
                        $kehu = \app\admin\model\dahui\Kehu::get(['idnumber' => $params['idnumber']]);
                        if ($kehu) {
                            $kehu->name = $params['name'];
                            $kehu->mobile = $params['mobile'];
                            $kehu->save();
                        } else {
                            $kehu = new \app\admin\model\dahui\Kehu;
                            $result2 = $kehu->allowField(true)->save($params);
                        }
                    }

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
//                    $this->success();
//                    $this->error("已添加成功, 继续加油！", null, '', 1);
                    $this->success("已添加成功！");
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
    }

    /**
     * 编辑 订单管理
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }

                    if (!isset($params['preprocessing'])) {
                        $params['preprocessing'] = "";
                    }
                    $params = $this->setquanxianlog($params);

                    if (isset($params['idnumber']) && strlen($params['idnumber']) > 10) {
                        $kehu = \app\admin\model\dahui\Kehu::get(['idnumber' => $params['idnumber']]);
                        if ($kehu) {
                            $kehu->name = $params['name'];
                            $kehu->mobile = $params['mobile'];
                            $kehu->save();
                        } else {
                            $kehu = new \app\admin\model\dahui\Kehu;
                            $result2 = $kehu->allowField(true)->save($params);
                        }
                    }

                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $Gongshi = new \app\admin\model\dahui\Gongshi;
        $companyList = collection($Gongshi->field('businesstype, name, minimumcardinality, proportion')->select())->toArray();
        $this->view->assign("companyList", $companyList);

        $row['name'] = "";
        $row['mobile'] = "";
        $kehu = \app\admin\model\dahui\Kehu::get(['idnumber' => $row['idnumber']]);
        if ($kehu) {
            $row['idnumber'] = $kehu->idnumber;
            $row['name'] = $kehu->name;
            $row['mobile'] = $kehu->mobile;
        }

        $companyList2 = collection($Gongshi->field('name')->where('businesstype', $row['businesstype'])->select())->toArray();
        $this->view->assign("companyList2", $companyList2);

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 编辑 补缴明细
     */
    public function edit1($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        $this->view->assign("refundornotList", $row->getRefundornotList());

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if (isset($params['kehu.mobile'])) {
                    $kehu = \app\admin\model\dahui\Kehu::get(['idnumber' => $row->idnumber]);
                    $kehu->mobile = $params['kehu.mobile'];
                    $kehu = $this->setquanxianlog2($kehu);
                    $kehu->save();
                    $this->success('客户电话修改成功');
                } else if (isset($params['paymentnumber'])) {
                    $row->paymentnumber = $params['paymentnumber'];
                    $row = $this->setquanxianlog2($row);
                    $row->save();
                    $this->success('缴纳号码修改成功');
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 编辑 补缴客户
     */
    public function edit2($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        $this->view->assign("refundornotList", $row->getRefundornotList());

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if (isset($params['paymentnumber'])) {
                    $row->paymentnumber = $params['paymentnumber'];
                    $row = $this->setquanxianlog2($row);
                    $row->save();
                    $this->success('缴纳号码修改成功');
                } else if (isset($params['monthspaid'])) {
                    $row->monthspaid = $params['monthspaid'];
                    $row = $this->setquanxianlog2($row);
                    $row->save();
                    $this->success('缴纳月数修改成功');
                } else if (isset($params['supplementarynote'])) {
                    $row->supplementarynote = $params['supplementarynote'];
                    $row = $this->setquanxianlog2($row);
                    $row->save();
                    $this->success('补缴备注修改成功');
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
    /**
     * 编辑 退款客户
     */
    public function edit3($ids = null)
    {
        $row = \app\admin\model\dahui\Nianyue::get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        $this->view->assign("refundornotList", $row->getRefundornotList());

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");

            if ($params) {
                $row->refundornot = $params['refundornot'];
                $row->save();
                $this->success('退款状态修改成功');
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids) {

            $row = $this->model->get($ids);

            $params = $row->toArray();
            $bujiao2 = new \app\admin\model\dahui\Bujiao2();
            $params['delman'] = $this->auth->nickname;
            unset($params['create_time']);
            $bujiao2->allowField(true)->save($params);

            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 编辑 客户电话
     */
    public function editkehumobile()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $idnumber = $params['idnumber'];
                $kehu = \app\admin\model\dahui\Kehu::get(['idnumber' => $idnumber]);
                $kehu->note = $params['note'];
                $kehu->save();
                $this->success('客户备注修改成功');
            }
            $this->error(__('Parameter %s can not be empty', ''));
        } else {
            $idnumber = $this->request->request('idnumber');
            $kehu = \app\admin\model\dahui\Kehu::where('idnumber', $idnumber)
                ->field('note')
                ->find();
            $row = [];
            $row['note'] = $kehu['note'];
            $row['idnumber'] = $idnumber;
            $this->view->assign("row", $row);
        }

        return $this->view->fetch();
    }

    /**
     * 编辑 客户备注
     */
    public function editkehunote()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $idnumber = $params['idnumber'];
                $kehu = \app\admin\model\dahui\Kehu::get(['idnumber' => $idnumber]);
                $kehu->note = $params['note'];
                $kehu->save();
                $this->success('客户备注修改成功');
            }
            $this->error(__('Parameter %s can not be empty', ''));
        } else {
            $idnumber = $this->request->request('idnumber');
            $kehu = \app\admin\model\dahui\Kehu::where('idnumber', $idnumber)
                ->field('note')
                ->find();
            $row = [];
            $row['note'] = $kehu['note'];
            $row['idnumber'] = $idnumber;
            $this->view->assign("row", $row);
        }

        return $this->view->fetch();
    }

    /**
     * 审核 订单管理  审核补缴不需要加入年月
     * "update 补缴 set 补缴年月=@p2,业务类型=@p3,淘宝名称=@p4,身份证号=@p5,缴纳号码=@p6,缴纳公司=@p7,
    缴纳基数=@p8,缴纳金额=@p9,缴纳月数=@p10,缴纳年月=@p11,付代理费=@p12,订单备注=@p13,审核状态=@p14,预处理=@p15
    where 订单编号=@p1"
     */
    public function audit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if ($row['auditstatus'] == '已审核') {
            $this->error(__('已审核的订单不能修改！'));
        }

        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }

                    if (isset($params['preprocessing']) && $params['preprocessing'] == '是') {
                        $this->error(__('预处理的订单不能审核！'));
                    } else {
                        $params['preprocessing'] = '';
                    }

                    $params = $this->setquanxianlog($params);

                    $kehu = \app\admin\model\dahui\Kehu::get(['idnumber' => $params['idnumber']]);
                    if ($kehu) {
                        $kehu->name = $params['name'];
                        $kehu->mobile = $params['mobile'];
                        $kehu = $this->setquanxianlog2($kehu);
                        $kehu->save();
                    } else {
                        $kehu = new \app\admin\model\dahui\Kehu;
                        $result2 = $kehu->allowField(true)->save($params);
                    }

                    $params['auditstatus'] = '已审核';
                    $result = $row->allowField(true)->save($params);

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $Gongshi = new \app\admin\model\dahui\Gongshi;
        $companyList = collection($Gongshi->field('businesstype, name, minimumcardinality, proportion')->select())->toArray();
        $this->view->assign("companyList", $companyList);

        $kehu = \app\admin\model\dahui\Kehu::get(['idnumber' => $row['idnumber']]);
        if ($kehu) {
            $row['idnumber'] = $kehu->idnumber;
            $row['name'] = $kehu->name;
            $row['mobile'] = $kehu->mobile;
        }

        $companyList2 = collection($Gongshi->field('name')->where('businesstype', $row['businesstype'])->select())->toArray();
        $this->view->assign("companyList2", $companyList2);

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 批量审核 订单管理
     */
    public function allaudit($ids = null)
    {
        $list = $this->model->where('id', 'in', $ids)->select();

        foreach ($list as $row) {
            if ($row->preprocessing == '是') {
                $this->error('预处理的订单不能审核！_' . $row->id);
                return;
            }
        }

        foreach ($list as $row) {
            if ($row['auditstatus'] == '已审核') {
                continue;
            }
            $row['preprocessing'] = '';
            $row = $this->setquanxianlog2($row);
            $row['auditstatus'] = '已审核';
            $row->save();

//            $kehu = \app\admin\model\dahui\Kehu::get(['idnumber' => $row['idnumber']]);
//            if ($kehu) {
//                $kehu->name = $row['name'];
//                $kehu->mobile = $row['mobile'];
//                $kehu = $this->setquanxianlog2($kehu);
//                $kehu->save();
//            } else {
//                $kehu = new \app\admin\model\dahui\Kehu;
//                $params['luruman'] = $this->auth->nickname;
//                $result2 = $kehu->allowField(true)->save($params);
//            }
        }

        $this->success();

    }

    /**
     * 补缴明细
     */
    public function index1()
    {
        if ($this->request->isAjax()) {
            $filter = $this->request->get("filter", '');
            $filter = (array)json_decode($filter, true);

            $offset = $this->request->get("offset", 0);
            $limit = $this->request->get("limit", 0);

            $idnumber = "";
            if (isset($filter['idnumber'])) {
                $idnumber = $filter['idnumber'];
            }
            $businesstype = "";
            if (isset($filter['businesstype'])) {
                $businesstype = $filter['businesstype'];
            }

            if (empty($idnumber)) {
                return json(array("total" => 0, "rows" => array(), "idnumber" => $idnumber, "note" => ''));
            }

            if (empty($businesstype)) {
                $list = $this->model
                    ->where('idnumber', $idnumber)
//                    ->with(['kehu'])
                    ->select();
            } else {
                $list = $this->model
//                    ->with(['kehu'])
                    ->where('idnumber', $idnumber)
                    ->where('businesstype', $businesstype)
                    ->select();
            }

            $kehu = \app\admin\model\dahui\Kehu::get(['idnumber' => $idnumber]);
            $kehu = $kehu->toArray();
            $list = collection($list)->toArray();
            foreach ($list as &$row) {
                $row['kehu'] = $kehu;

                if ($limit == 0) {
                    //导出
//                    $row['idnumber'] = $this->importstr($row['idnumber']);
//                    $row['paymentnumber'] = $this->importstr($row['paymentnumber']);
                }
            }

            $result = array("total" => count($list), "rows" => $list, "idnumber" => $idnumber, "note" => $kehu['note']);

            return json($result);
        }

        return $this->view->fetch();
    }

    /**
     * 补缴客户
     */
    public function index2()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->with(['kehu'])
                ->where($where)
                ->where('auditstatus', '已审核')
                ->where('refundornot', '')
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->with(['kehu'])
                ->where($where)
                ->where('auditstatus', '已审核')
                ->where('refundornot', '')
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();
            if ($limit == 0) {
                //导出
//                foreach ($list as &$row) {
//                    $row['idnumber'] = $this->importstr($row['idnumber']);
//                    $row['paymentnumber'] = $this->importstr($row['paymentnumber']);
//                }
            }

            $money = $this->model
                ->with(['kehu'])
                ->where($where)
                ->where('auditstatus', '已审核')
                ->where('refundornot', '')
                ->sum('paymentamount');

            $result = array("total" => $total, "rows" => $list, "extend" => ['money' => intval($money)]);


            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 退款客户
     */
    public function index3()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->with(['kehu'])
                ->where($where)
                ->where('refundornot', '<>', '')
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->with(['kehu'])
                ->where($where)
                ->where('refundornot', '<>', '')
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();
            if ($limit == 0) {
                //导出
//                foreach ($list as &$row) {
//                    $row['idnumber'] = $this->importstr($row['idnumber']);
//                    $row['paymentnumber'] = $this->importstr($row['paymentnumber']);
//                }
            }

            $money = $this->model
                ->with(['kehu'])
                ->where($where)
                ->where('refundornot', '<>', '')
                ->order($sort, $order)
                ->sum('paymentamount');

            $result = array("total" => $total, "rows" => $list, "extend" => ['money' => intval($money)]);


            return json($result);
        }

        return $this->view->fetch();
    }

    /**
     * 是否退款 状态
     */
    //http://dahui.test/admin/dahui/bujiao/changetstatus
    public function changetstatus($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if ($this->tuikuan) {
            if ($row->refundornot == '') {
                $row->refundornot = '待退款';
            } else if ($row->refundornot == '待退款') {
                $row->refundornot = '已退款';
            } else if ($row->refundornot == '已退款') {
                $row->refundornot = '需退款';
            } else if ($row->refundornot == '需退款') {
                $row->refundornot = '';
            }
        } else if ($this->caozuo) {
            if ($row->refundornot == '') {
                $row->refundornot = '需退款';
            } else if ($row->refundornot == '需退款') {
                $row->refundornot = '';
            }
        } else if ($this->audit) {
            if ($row->refundornot == '') {
                $row->refundornot = '待退款';
            } else if ($row->refundornot == '待退款') {
                $row->refundornot = '需退款';
            } else if ($row->refundornot == '需退款') {
                $row->refundornot = '';
            }
        }

        $row = $this->setquanxianlog2($row);

        $row->save();
        $this->success("退款状态修改成功", null, ['refundornot' => $row->refundornot]);
    }

    //退款员
    //从待退款状态 点击后 变更为 已退款（另外有时候误操作情况下 他可以把已退款变更为  --状态 让其他角色重新操作）
    public function changetstatus4($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if ($row->refundornot == '待退款') {
            $row->refundornot = '已退款';
        } else if ($row->refundornot == '已退款') {
            $row->refundornot = '';
        } else if ($row->refundornot == '') {
            $row->refundornot = '已退款';
        }

        $row->save();
        $this->success("退款状态修改成功", null, ['refundornot' => $row->refundornot]);

    }

    /**
     * 是否退款 状态 --操作人员
     */
    //http://dahui.test/admin/dahui/bujiao/changetstatus2
    public function changetstatus2($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        $msg = '无修改权限';
        if ($row->refundornot == '') {
            $row->refundornot = '需退款';
            $msg = '退款状态修改成功';
        } else if ($row->refundornot == '需退款') {
            $row->refundornot = '';
            $msg = '退款状态修改成功';
        }

        $row = $this->setquanxianlog2($row);

        $row->save();
        $this->success($msg, null, ['refundornot' => $row->refundornot]);

    }

    /**
     * 补缴状态++
     */
    //http://dahui.test/admin/dahui/bujiao/changebjstatus
    public function changebjstatus($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if ($row->overduestatus == '未办理') {
            $row->overduestatus = '已办理';
        } else if ($row->overduestatus == '已办理') {
            $row->overduestatus = '部分失败';
        } else if ($row->overduestatus == '部分失败') {
            $row->overduestatus = '未办理';
        }

        $row = $this->setquanxianlog2($row);

        $row->save();
        $this->success("补缴状态修改成功", null, ['overduestatus' => $row->overduestatus]);
    }

    const TBAOMING = "__taobaoname__";
    const IDNUMBER = "__idnumber__";
    //http://dahui.test/admin/dahui/bujiao/lsdd?taobaoname=-jjjj-
    //显示此淘宝号，办理过的个人订单
    public function lsdd()
    {
//        select 业务类型,订单.身份证号,客户姓名,客户电话,缴纳号码,缴纳公司,
//                缴纳基数,缴纳金额,缴纳年月,付代理费 from 订单 left join 客户 on 订单.身份证号=客户.身份证号
//                where 淘宝名称=@p1 and 预处理!=@p2 order by 订单.身份证号 asc,业务类型 asc,下单日期 desc
        if ($this->request->isAjax()) {
            $taobaoname = Session::get(self::TBAOMING);
            $idnumber = Session::get(self::IDNUMBER);

            if (!empty($taobaoname)) {
                $sql = "select d.*, kehu.name as kehuname, kehu.mobile as kehumobile from fa_dahui_dingdan d INNER join fa_dahui_kehu kehu on d.idnumber=kehu.idnumber
	where taobaoname = '".$taobaoname."' and preprocessing != '是' order by idnumber asc, CONVERT(`businesstype` USING gbk) asc, orderdate desc";
            } else if (!empty($idnumber)) {
                $sql = "select d.*, kehu.name as kehuname, kehu.mobile as kehumobile from fa_dahui_dingdan d INNER join fa_dahui_kehu kehu on d.idnumber=kehu.idnumber
	where d.idnumber = '".$idnumber."' and preprocessing != '是' order by idnumber asc, CONVERT(`businesstype` USING gbk) asc, orderdate desc";
            } else {
                $list = [];
                $result = array("total" => 0, "rows" => $list);
                return json($result);
            }

            $list = Db::query($sql);

            $total = count($list);
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        } else {

            $taobaoname = $this->request->request('taobaoname', '');
            $idnumber = $this->request->request('idnumber', '');

            Session::set(self::TBAOMING, $taobaoname);
            Session::set(self::IDNUMBER, $idnumber);

        }

        return $this->view->fetch();
    }

    //淘宝关联订单，加入
    public function addhis($ids)
    {
        if ($this->request->isPost()) {

            $sql = "select d.*, kehu.name as kehuname, kehu.mobile as kehumobile from fa_dahui_dingdan d INNER join fa_dahui_kehu kehu on d.idnumber=kehu.idnumber where d.id = " . $ids . " limit 1";
            $list = Db::query($sql);
            $this->success('success', null, $list[0]);
        }
        $this->error(__('没有选中历史业务'));

    }

    //设置权限记录
    function setquanxianlog($params)
    {
        if (!$params) {
            return $params;
        }
        $audit = $this->auth->check('dahui/dingdan/audit');
        $luru = $this->auth->check('dahui/dingdan/luru');
        $caozuo = $this->auth->check('dahui/dingdan/caozuo');
        $admin = $audit;

        if ($audit) {
            //审核员和管理员
            $params['auditman'] = $this->auth->nickname;
        } else if ($luru) {
            $params['luruman'] = $this->auth->nickname;
        } else if ($caozuo) {
            $params['opman'] = $this->auth->nickname;
        }

        return $params;
    }

    function setquanxianlog2($row)
    {
        if (!$row) {
            return $row;
        }
        $audit = $this->auth->check('dahui/dingdan/audit');
        $luru = $this->auth->check('dahui/dingdan/luru');
        $caozuo = $this->auth->check('dahui/dingdan/caozuo');
        $admin = $audit;

        if ($audit) {
            //审核员和管理员
            $row->auditman = $this->auth->nickname;
        } else if ($luru) {
            $row->luruman = $this->auth->nickname;
        } else if ($caozuo) {
            $row->opman= $this->auth->nickname;
        }

        return $row;
    }

    //批量补缴状态 未办理
    public function plbjstatus0($ids = null)
    {
        $list = \app\admin\model\dahui\Bujiao::where('id', 'in', $ids)->select();

        foreach ($list as $row) {
            $row->overduestatus = '未办理';
            $row = $this->setquanxianlog2($row);
            $row->save();

        }
        $this->success();
    }

    //批量补缴状态
    public function plbjstatus1($ids = null)
    {
        $list = \app\admin\model\dahui\Bujiao::where('id', 'in', $ids)->select();

        foreach ($list as $row) {
            $row->overduestatus = '已办理';
            $row = $this->setquanxianlog2($row);
            $row->save();

        }
        $this->success();
    }

    public function plbjstatus2($ids = null)
    {
        $list = \app\admin\model\dahui\Bujiao::where('id', 'in', $ids)->select();

        foreach ($list as $row) {
            $row->overduestatus = '部分失败';
            $row = $this->setquanxianlog2($row);
            $row->save();

        }
        $this->success();
    }
}
